package com.abel.demo.config.apiversion;

import com.abel.demo.anno.ApiVersion;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.web.servlet.mvc.condition.RequestCondition;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import java.lang.reflect.Method;

/**
 * Author: Abel.lin
 * Date: 2021/6/30 11:20
 * Company: Abel.Studio
 * Description:
 */
@Slf4j
public class ApiHandlerMapping extends RequestMappingHandlerMapping {
    @Override
    protected RequestCondition<?> getCustomTypeCondition(Class<?> handlerType) {
        if(handlerType.getName().startsWith("com.abel")) {
            return buildFrom(AnnotationUtils.findAnnotation(handlerType, ApiVersion.class));
        }
        return super.getCustomTypeCondition(handlerType);
    }


    @Override
    protected RequestCondition<?> getCustomMethodCondition(Method method) {
        if(method.getDeclaringClass().getName().startsWith("com.abel")){
            return buildFrom(AnnotationUtils.findAnnotation(method, ApiVersion.class));
        }
        return super.getCustomMethodCondition(method);
    }

    private ApiCondition buildFrom(ApiVersion platform) {
        return platform == null ? new ApiCondition("1.0.0") :
                new ApiCondition(platform.value());
    }
}
